package com.example.plant.util.http

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.util.Log
import com.example.plant.broadcast.GetPlantClassifyResultBroadCast
import com.example.plant.util.http.Bean.ClassifyBean
import com.example.plant.util.http.Bean.ResultBean
import com.example.plant.util.images.Base64Util
import com.google.gson.JsonObject
import org.json.JSONObject
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object httpUtil {
        private const val TAG = "ImageClassifyUtil"

        /**
         * 请求tokenurl
         */
        val REQUEST_TOKEN_URL = "https://aip.baidubce.com/"

        /**
         * AI接口请求url
         */
        val REQUEST_URL = "https://aip.baidubce.com/"

        //设置AK/SK
        var ACCESS_TOKEN:String = ""
        val API_KEY = "XQsG9utGDbXzQzINRfQb176P"
        val SECRET_KEY = "1KWLp7iFhZ9uWmiHz3RLfvqvbybFVZkA"




    val retrofit = Retrofit.Builder()
        .baseUrl(REQUEST_TOKEN_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    var getMyToken= retrofit.create(GetToken::class.java);

    var get_classify= retrofit.create(GetClassify::class.java);

    fun send() {
        getMyToken.send("client_credentials", API_KEY, SECRET_KEY)
            .enqueue(object : Callback<ResultBean> {
                    override fun onFailure(call: retrofit2.Call<ResultBean>, t: Throwable) {
                        var i:Int =1;
                        System.out.println(t.localizedMessage)
                    }

                    override fun onResponse(call: retrofit2.Call<ResultBean>, response: Response<ResultBean>) {
                        ACCESS_TOKEN = response.body()?.access_token ?: "132"
                    }
                }
            )
    }

    fun getClassify(bitmap: Bitmap,context:Context)
    {
        val image=Base64Util.bitmapToBase64(bitmap)
        image?.let {
            get_classify.getClassify(httpUtil.ACCESS_TOKEN, it)
                .enqueue(object : Callback<ClassifyBean> {
                    override fun onFailure(call: retrofit2.Call<ClassifyBean>, t: Throwable) {
                        Log.d("请求失败！",t.message.toString())
                    }
                    override fun onResponse(call: retrofit2.Call<ClassifyBean>, response: Response<ClassifyBean>) {
                        Log.d("请求成功！", response.body()?.result?.get(0)?.name ?:"00")
                        var str:String=response.body()?.result?.get(0)?.name ?:"好像不是植物"
                        var intent=Intent();
                        intent.putExtra(GetPlantClassifyResultBroadCast.list.RECOGNIZED_INFO,str);
                        intent.setAction("getPlantClassifyResult")
                        context.sendBroadcast(intent)
                    }
                }
                )
        }
    }

}